﻿using Medlcalcare.MVC.Common;
using Medlcalcare.MVC.Model;
using Newtonsoft.Json;
using Polly;
using System.Net.Http.Headers;
using System.Text;

namespace Medlcalcare.MVC.Servicesa
{
    /// <summary>
    /// DeepSeek 大模型服务实现类
    /// 职责：封装与大模型API的交互逻辑
    /// </summary>
    public class DeepSeekServicea : IDeepSeekServicea
    {
        private readonly HttpClient _httpClient;
        private readonly IConfiguration _config;

        // 通过依赖注入获取 HttpClient 和配置
        public DeepSeekServicea(HttpClient httpClient, IConfiguration config)
        {
            _httpClient = httpClient;
            _config = config;
        }

        /// <summary>
        /// 获取诊断建议（核心方法）
        /// </summary>
        /// <param name="request">包含症状和病史的请求对象</param>
        /// <returns>结构化的诊断结果</returns>
        public async Task<DiagnosisResult> GetDiagnosisSuggestionAsync(DiagnosisRequest request)
        {
            // 构建医学专业提示词模板
            // 注意：此处Prompt设计直接影响大模型输出质量
            var prompt = @$"
            作为三甲医院主任医师，请分析以下患者信息：
            主诉：{request.Symptoms}
            病史：{request.PatientHistory ?? "无"}
            请按以下格式回复：
            1. 可能疾病（按概率排序）
            2. 建议检查项目
            ";

            // 构造符合DeepSeek API要求的请求体
            var requestBody = new
            {
                model = "deepseek-chat",       // 指定模型版本
                messages = new[] { new { role = "user", content = prompt } },//user指定用户和prompt模板
                temperature = 0.2              // 低随机性保证医学严谨性，避免模型输出错误
            };

            // 创建HTTP请求消息
            var requestMessage = new HttpRequestMessage(HttpMethod.Post, _config["DeepSeek:Endpoint"])
            {
                Headers = {
                    //Bearer验证然后获取到APIKey
                Authorization = new AuthenticationHeaderValue("Bearer", _config["DeepSeek:ApiKey"])
            },
                //内容（就是参数）序列化
                Content = new StringContent(
                    JsonConvert.SerializeObject(requestBody),
                    Encoding.UTF8,
                    "application/json")
            };

            try
            {
                // 发送请求并获取响应
                var response = await _httpClient.SendAsync(requestMessage);
                response.EnsureSuccessStatusCode(); // 确保HTTP状态码成功

                // 解析响应内容
                var content = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<dynamic>(content)!;

                // 将大模型的自由文本响应转换为结构化对象
                return ParseDeepSeekResponse(result.choices[0].message.content.ToString());
            }
            catch (HttpRequestException ex)
            {
                // 记录日志并抛出业务异常
                throw new MedicalAIException("大模型服务调用失败", ex);
            }
        }

        /// <summary>
        /// 解析大模型返回的原始文本
        /// </summary>
        /// <param name="rawText">模型输出的原始文本</param>
        /// <returns>结构化的诊断结果对象</returns>
        private DiagnosisResult ParseDeepSeekResponse(string rawText)
        {
            // 示例解析逻辑（根据实际输出格式调整）
            //var sections = rawText.Split('\n');
            var sections = rawText.Replace("\n", "&lt;br&gt;");
            return new DiagnosisResult
            {
                PossibleDiseases = FormatMedicalDiagnosis(rawText),
                RecommendedTests = rawText
            };
        }

        public string FormatMedicalDiagnosis(string input)
        {
            var sections = input.Split(new[] { "2. " }, StringSplitOptions.None);
            var diseasesSection = sections[0].Replace("1. ", "").Trim();
            var testsSection = "2. " + sections[1].Trim();

            var diseases = ParseDiseasesSection(diseasesSection);
            var tests = ParseTestsSection(testsSection);

            var sb = new StringBuilder();

            // 格式化疾病部分
            sb.AppendLine("### 1. 可能疾病（按概率排序）");
            sb.AppendLine();

            foreach (var disease in diseases)
            {
                sb.AppendLine($"- **{disease.Title}**");
                foreach (var detail in disease.Details)
                {
                    sb.AppendLine($"  - {detail}");
                }
                sb.AppendLine();
            }

            // 格式化检查项目部分
            sb.AppendLine("---");
            sb.AppendLine();
            sb.AppendLine("### 2. 建议检查项目");
            sb.AppendLine();

            foreach (var testGroup in tests)
            {
                sb.AppendLine($"#### {testGroup.Title}：");
                foreach (var test in testGroup.Details)
                {
                    sb.AppendLine($"- {test}");
                }
                foreach (var subGroup in testGroup.SubItems)
                {
                    sb.AppendLine($"  - {subGroup.Title}");
                    foreach (var item in subGroup.Details)
                    {
                        sb.AppendLine($"    - {item}");
                    }
                }
                sb.AppendLine();
            }

            // 添加备注
            var noteIndex = input.IndexOf("注：");
            if (noteIndex >= 0)
            {
                sb.AppendLine("---");
                sb.AppendLine();
                sb.AppendLine($"**备注**：{input.Substring(noteIndex + 2)}");
            }

            return sb.ToString();
        }

        private List<DiagnosisItem> ParseDiseasesSection(string text)
        {
            var diseases = new List<DiagnosisItem>();
            var diseaseParts = text.Split(new[] { " - **" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var part in diseaseParts)
            {
                if (string.IsNullOrWhiteSpace(part)) continue;

                var colonIndex = part.IndexOf("**：");
                if (colonIndex < 0) continue;

                var disease = new DiagnosisItem
                {
                    Title = part.Substring(0, colonIndex).Trim(),
                    Details = new List<string>()
                };

                var details = part.Substring(colonIndex + 3).Trim();
                disease.Details.Add(details);

                diseases.Add(disease);
            }

            return diseases;
        }

        private List<DiagnosisItem> ParseTestsSection(string text)
        {
            var tests = new List<DiagnosisItem>();
            var testGroups = text.Split(new[] { " - **" }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var group in testGroups)
            {
                if (string.IsNullOrWhiteSpace(group)) continue;

                var colonIndex = group.IndexOf("**：");
                if (colonIndex < 0) continue;

                var testGroup = new DiagnosisItem
                {
                    Title = group.Substring(0, colonIndex).Trim(),
                    Details = new List<string>(),
                    SubItems = new List<DiagnosisItem>()
                };

                var content = group.Substring(colonIndex + 3).Trim();

                // 处理子项目
                var subItems = content.Split(new[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                foreach (var item in subItems)
                {
                    if (item.Contains("（视情况选择）"))
                    {
                        // 这是子组标题
                        var subGroup = new DiagnosisItem
                        {
                            Title = item.Replace("（视情况选择）", "").Trim(),
                            Details = new List<string>()
                        };
                        testGroup.SubItems.Add(subGroup);
                    }
                    else if (testGroup.SubItems.Count > 0)
                    {
                        // 添加到最后一个子组
                        testGroup.SubItems[^1].Details.Add(item.Trim());
                    }
                    else
                    {
                        // 添加到主组
                        testGroup.Details.Add(item.Trim());
                    }
                }

                tests.Add(testGroup);
            }

            return tests;
        }

    }
    public class DiagnosisItem
    {
        public string Title { get; set; }
        public List<string> Details { get; set; } = new List<string>();
        public List<DiagnosisItem> SubItems { get; set; } = new List<DiagnosisItem>();
    }
}
